package com.kitty.game.npc.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kitty.common.model.Pos;
import com.kitty.common.utils.SpringUtils;
import com.kitty.game.activity.model.product.ActivityType;
import com.kitty.game.activity.service.time.XingGuanHandler;
import com.kitty.game.base.service.BagService;
import com.kitty.game.config.*;
import com.kitty.game.enter.RespDisappear;
import com.kitty.game.enter.RespGeneralNotify;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.equip.model.RoleEquip;
import com.kitty.game.equip.service.EquipService;
import com.kitty.game.fight.service.BroadcastService;
import com.kitty.game.fight.service.FightExecutorService;
import com.kitty.game.fixed.service.FixedTeamService;
import com.kitty.game.i18n.I18nIdDataPool;
import com.kitty.game.item.message.RespBuyBackList;
import com.kitty.game.jiutian.MSGJiuTianRespMasterInfo;
import com.kitty.game.map.service.MapService;
import com.kitty.game.mount.message.RespSubmitMultiItem;
import com.kitty.game.npc.NpcDataPool;
import com.kitty.game.npc.message.RespNpcContent;
import com.kitty.game.npc.message.RespNpcLeave;
import com.kitty.game.npc.message.RespOpenGuess;
import com.kitty.game.npc.model.NpcButtonParam;
import com.kitty.game.npc.model.NpcContentParam;
import com.kitty.game.npc.service.appreace.AppearanceHandler;
import com.kitty.game.onlinemall.service.MallService;
import com.kitty.game.pay.message.RespPayUrl;
import com.kitty.game.pet.message.RespDestroyValuableList;
import com.kitty.game.pet.model.Pet;
import com.kitty.game.pet.model.PetBook;
import com.kitty.game.pet.service.PetService;
import com.kitty.game.player.model.PlayerExtendBox;
import com.kitty.game.role.message.RespAppear;
import com.kitty.game.role.model.Role;
import com.kitty.game.role.service.RoleService;
import com.kitty.game.school.service.SchoolService;
import com.kitty.game.shop.ItemInfo;
import com.kitty.game.shop.RespGoodsList;
import com.kitty.game.shop.ShopDataPool;
import com.kitty.game.shop.ShopService;
import com.kitty.game.talk.service.TalkService;
import com.kitty.game.task.service.NewTaskService;
import com.kitty.game.team.message.RespMsg;
import com.kitty.game.team.model.Team;
import com.kitty.game.team.service.TeamService;
import com.kitty.game.utils.Const;
import com.kitty.game.utils.NotifyModules;
import com.kitty.game.wawa.service.WawaService;
import com.kitty.mina.cache.DataCache;
import com.kitty.mina.message.MessagePusher;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.lang.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Consumer;
import java.util.function.Function;

@Service
@Slf4j
public class NewNpcService {


    @Autowired
    BroadcastService broadcastService;

    /**
     * 请求NPC的内容
     *
     * @param role
     * @param npcId NPC的 ID
     */
    public void requestNpcContent(Role role, int npcId) {
        // TODO 暂时只处理主线任务相关的内容，其他内容后面需要加上
        NPC npc = SpringUtils.getBean(MapService.class).getNpc(npcId);
        if (npc == null) {
            SchoolService schoolService = SpringUtils.getBean(SchoolService.class);
            byte toFightSchool = schoolService.getToFightSchool((byte) role.getPolar());
            npc = schoolService.getNpc(npcId, toFightSchool);
        }

        if (npc == null) {
            log.info("1npc找不到 roleId: {}, npcId: {}", role.getRoleId(), npcId);
            NPC npc1 = DataCache.TIANBING_NPCS.get(npcId);
            if(npc1 == null){
                    return;
                }
                npc = npc1;
        }
//        /**不能点击NPC时，则不处理*/
//        if (!canClickNpc(role, npc)) {
//            log.info("不能点击NPC roleId: {}, npcId: {}", role.getRoleId(), npcId);
//            return;
//        }

        Consumer<NpcContentParam> npcContentHandler = NpcDataPool.npcContentHandlers.get(npc.getType());
        if (npcContentHandler != null) {
            npcContentHandler.accept(new NpcContentParam(role, npc));
            return;
        }

        /**生成响应的内容*/
        /**获得npc的content进行设置*/
        String content = getNpcContent(role, npc);
        sendNpcContent(role, npc, content);
    }

    /**
     * 请求NPC的内容 //不做距离验证的npc
     *
     * @param role
     * @param npcId NPC的 ID
     */
    public void requestNpcContent(Role role, int npcId,String content) {
        // TODO 暂时只处理主线任务相关的内容，其他内容后面需要加上
        NPC npc = SpringUtils.getBean(MapService.class).getNpc(npcId);
        if (npc == null) {
            SchoolService schoolService = SpringUtils.getBean(SchoolService.class);
            byte toFightSchool = schoolService.getToFightSchool((byte) role.getPolar());
            npc = schoolService.getNpc(npcId, toFightSchool);
        }
//        /**npc找不到时，则不处理*/
//        if (npc == null) {
//            log.info("npc找不到 roleId: {}, npcId: {}", role.getRoleId(), npcId);
//            return;
//        }
        if (npc == null) {
            log.info("2npc找不到 roleId: {}, npcId: {}", role.getRoleId(), npcId);
            NPC npc1 = DataCache.TIANBING_NPCS.get(npcId);

            if(npc1 == null){
                return;
            }
            npc = npc1;
        }
        Consumer<NpcContentParam> npcContentHandler = NpcDataPool.npcContentHandlers.get(npc.getType());
        if (npcContentHandler != null) {
            npcContentHandler.accept(new NpcContentParam(role, npc));
            return;
        }
        sendNpcContent2(role, npc, content);
    }

    /**
     * 获得NPC的content
     */
    public String getNpcContent(Role role, NPC npc) {
        String spectialButtons = getSpectialButtons(role, npc);
        if (spectialButtons == null) {
            return SpringUtils.getBean(NewTaskService.class).getNpcContent(role, npc);
        }

        String content = SpringUtils.getBean(NewTaskService.class).getNpcContent(role, npc);
        /**按钮显示在倒数第二的位置*/
        int index = content.lastIndexOf("[", content.length());
        if (index > 0) {
            return content.substring(0, index-1) + spectialButtons + content.substring(index, content.length());
        } else {
            return content + spectialButtons;
        }
    }

    private String getSpectialButtons(Role role, NPC npc) {
        if (NpcDataPool.spetialButtons.containsKey(npc.getId())) {
            StringBuilder stringBuilder = null;
            List<Function<Role, String>> functions = NpcDataPool.spetialButtons.get(npc.getId());
            for (Function<Role, String> function : functions) {
                String button = function.apply(role);
                if (button == null) {continue;}

                if (stringBuilder == null) {stringBuilder = new StringBuilder();}
                stringBuilder.append(button);
            }
            if (stringBuilder != null) {return stringBuilder.toString();}
        }
        return null;
    }

    /***
     * 点击npc按钮处理
     * @param role
     * @param npcId NPC的 ID
     * @param msg 选择按钮后返回的信息，可以识别选择了哪个按钮
     */
    public void clickNpcButton(Role role, int npcId, String msg, String para) {
        /**关闭NPC对话框*/
        RespNpcLeave respNpcLeave = new RespNpcLeave();
        respNpcLeave.setNpcId(npcId);
        SpringUtils.getBean(TeamService.class).pushMessage(role, respNpcLeave);

        /**选择哪个按钮信息都没有，则不处理*/
        if (msg == null) {
            return;
        }

        NPC npc = null;
        /**使用物品时显示的按钮，npcId值并不是npc的id*/
        if (!NpcDataPool.itemButtons.contains(msg)) {
            npc = SpringUtils.getBean(MapService.class).getNpc(npcId);
            if (npc == null) {
                SchoolService schoolService = SpringUtils.getBean(SchoolService.class);
                byte toFightSchool = schoolService.getToFightSchool((byte) role.getPolar());
                npc = schoolService.getNpc(npcId, toFightSchool);
            }
            if (npc == null) {
                log.info("3npc找不到 roleId: {}, npcId: {}", role.getRoleId(), npcId);
                NPC npc1 = DataCache.TIANBING_NPCS.get(npcId);
                if(npc1 == null){
                    return;
                }
                npc = npc1;
            }

//            /**不能点击NPC时，则不处理*/
//            if (!canClickNpc(role, npc)) {
//                return;
//            }
        }

        /**处理按钮选择*/
        handleButtonChoose(role, npc, msg, para);
    }

    /**
     * 处理按钮选择
     */
    public void handleButtonChoose(Role role, NPC npc, String msg, String para) {
        // TODO 需要判断下这个NPC是否有这个按钮？


        // TODO 先用if else方式处理，后续再看怎么优化
        log.info("msg:::::"+msg);
        Consumer<NpcButtonParam> npcButtonHandler = NpcDataPool.npcButtonHandlers.get(msg);
        log.info("msg:::::"+JSON.toJSON(npcButtonHandler));
        if (npcButtonHandler != null) {
            npcButtonHandler.accept(new NpcButtonParam(role, npc, msg, "1".equals(para)));
            return;
        }

        for (Map.Entry<String, Consumer<NpcButtonParam>> entry : NpcDataPool.npcButtonPrefixHandlers.entrySet()) {
            if (msg.startsWith(entry.getKey())) {
                Consumer<NpcButtonParam> npcButtonPrefixHandler = entry.getValue();
                npcButtonPrefixHandler.accept(new NpcButtonParam(role, npc, msg, "1".equals(para)));
                return;
            }
        }
        if (msg.startsWith("ZHJ")){
            npcButtonHandler = NpcDataPool.npcButtonHandlers.get("ZHJ");
            npcButtonHandler.accept(new NpcButtonParam(role, npc, msg, "1".equals(para)));
        }
        if (msg.startsWith("dwdr")){
            npcButtonHandler = NpcDataPool.npcButtonHandlers.get("dwdr");
            npcButtonHandler.accept(new NpcButtonParam(role, npc, msg, "1".equals(para)));
        }
        if (msg.startsWith("改")){
            npcButtonHandler = NpcDataPool.npcButtonHandlers.get("GSG");
            npcButtonHandler.accept(new NpcButtonParam(role, npc, msg, "1".equals(para)));
        }
        if (msg.startsWith("HDDS")){
            npcButtonHandler = NpcDataPool.npcButtonHandlers.get("HDDS");
            npcButtonHandler.accept(new NpcButtonParam(role, npc, msg, "1".equals(para)));
        }
        if (msg.startsWith("积分回收宠物")){
            npcButtonHandler = NpcDataPool.npcButtonHandlers.get("积分回收贵重宠物");
            npcButtonHandler.accept(new NpcButtonParam(role, npc, msg, "1".equals(para)));
        }
        if (msg.startsWith("洗练天书") || msg.startsWith("xilianshuxing")){
            npcButtonHandler = NpcDataPool.npcButtonHandlers.get("洗练金色天书");
            npcButtonHandler.accept(new NpcButtonParam(role, npc, msg, "1".equals(para)));
        }
        if (msg.startsWith("selectsuperbook_")){
           getManBook(role,msg);
        }
    }

    /**
     * 发送i18nid对应的内容给NPC
     */
    public void sendNpcContent(Role role, NPC npc, int i18nId) {
        String content = I18nIdDataPool.getI18nContent(i18nId);
        sendNpcContent(role, npc, content);
    }

    /**
     * 发送i18nid对应的内容给NPC
     */
    public void sendNpcContent(Role role, NPC npc, int i18nId, Object... args) {
        String content = I18nIdDataPool.getI18nContent(i18nId, args);
        sendNpcContent(role, npc, content);
    }

    /**
     * 发送NPC提示信息
     */
    public void sendNpcContent(Role role, NPC npc, String content) {
        if (StringUtils.isNotEmpty(content) && npc != null) {
            /**返回提示信息*/
            RespNpcContent respNpcContent = getRespNpcContent(role, npc, content);
            if(npc.getId() == 15024 ||npc.getId() == 15025  ||npc.getId() == 15019){
                respNpcContent.setAttrib((byte)1);
                MessagePusher.pushMessage(role, respNpcContent);
            }else{
                sendRespNpcContent(role, respNpcContent);
            }
        }
    }

    /**
     * 发送NPC提示信息
     */
    public void sendNpcContent2(Role role, NPC npc, String content) {
        /**返回提示信息*/
        RespNpcContent respNpcContent = getRespNpcContent(role, npc, content);
        respNpcContent.setAttrib((byte)1);
        MessagePusher.pushMessage(role, respNpcContent);
    }

    /*  add tao 生成纯粹的contetn RespNpcContetn对象*/
    public void sendPurNpcContent(Role role, NPC npc, String content) {
        if (StringUtils.isNotEmpty(content) && npc != null) {
            RespNpcContent respNpcContent = this.getPureRespNpcContent(role, npc, content);
            this.sendRespNpcContent(role, respNpcContent);
        }
    }

    public RespNpcContent getPureRespNpcContent(Role role, NPC npc, String content) {
        RespNpcContent respNpcContent = new RespNpcContent();
        respNpcContent.setNpcName(npc.getName());
        respNpcContent.setNpcId(npc.getId());
        respNpcContent.setContent(content);
        respNpcContent.setNpcIcon(npc.getIcon());
        return respNpcContent;
    }
    // add:e


    public RespNpcContent getRespNpcContent(Role role, NPC npc, String content) {
        RespNpcContent respNpcContent = new RespNpcContent();
        respNpcContent.setNpcName(npc.getName());
        respNpcContent.setNpcId(npc.getId());
        respNpcContent.setContent(content);
        respNpcContent.setNpcIcon(npc.getIcon());
        AppearanceHandler appearanceHandler = NpcDataPool.appearanceHandlers.get(npc.getId());
        if (appearanceHandler != null) {
            appearanceHandler.changeRespNpcContent(role, npc, respNpcContent);
        }
        return respNpcContent;
    }

    public void sendRespNpcContent(Role role, RespNpcContent respNpcContent) {
        SpringUtils.getBean(TeamService.class).pushMessage(role, respNpcContent);
    }

    /**
     * 弹出任务对话
     */
    public void popTaskTalk(Role role, NPC npc, String msg) {
        int taskId = Integer.valueOf(msg.replace(NpcDataPool.TASK_TALK_PREFIX, ""));
        popTaskTalk(role, npc, taskId);
    }

    /**
     * 弹出任务对话
     */
    public void popTaskTalk(Role role, NPC npc, int taskId) {
        NewTaskService taskService = SpringUtils.getBean(NewTaskService.class);
        TaskSet taskSet = taskService.getTaskSet(taskId, role);
        /**找不到这个任务时，则不处理*/
        if (taskSet == null) {
            return;
        }

        TalkSet talkSet = taskService.getTalkMatchNpc(role, taskSet, npc);
        /**找不到对话时，则不处理*/
        if (talkSet == null) {
            return;
        }

        /**弹出对话*/
        SpringUtils.getBean(TalkService.class).popFirstTalk(role, talkSet);
    }

    /**
     * 判断是否可以点击，比如玩家是否在NPC所在地图，与NPC是否过远
     */
    private boolean canClickNpc(Role role, NPC npc) {
        /**判断是否组队，组队时则按组队逻辑判断，否则按个人逻辑判断*/
        if(npc.getId() == 15024 || npc.getName().contains("年兽") ||npc.getId() == 15025 || npc.getId() ==  15019 ){
            return true;
        }
        TeamService teamService = SpringUtils.getTeamService();
        if (teamService.isInTeam(role) == false) {

            Pos position = role.getPos();
            /**玩家所在地图与NPC所在地图不一致时，则返回false*/
            if (role.getPos().getMapId() != npc.getMapId()) {
//                MessagePusher.pushMessage(role, new RespMsg("当前位置距离NPC过远..."));  todo 如果不在一个地图 不给提示
                return false;
            }

            /**超过可点击范围时，则返回false*/
            int roleX = position.getX();
            int roleY = position.getY();

            if (Math.abs(roleX - npc.getX()) > NpcDataPool.NPC_CAN_CLICK_PERIMETER || Math.abs(roleY - npc.getY()) > NpcDataPool.NPC_CAN_CLICK_PERIMETER) {
//                MessagePusher.pushMessage(role, new RespMsg("当前位置距离NPC过远..."));
                return false;
            }
        } else {
            Team team = teamService.getTeam(role.getRoleId());
            /**只有队长才能操作*/
            if (!team.isLeader(role.getRoleId())) {
                MessagePusher.pushMessage(role, new RespMsg(Const.NOT_LEADER));
                return false;
            }

            /**只判断队长地图和距离*/
            if (role.getPos().getMapId() != npc.getMapId()) {
                return false;
            }

//            /**超过可点击范围时，则返回false*/
            int roleX = role.getPos().getX();
            int roleY = role.getPos().getY();

            if (Math.abs(roleX - npc.getX()) > NpcDataPool.NPC_CAN_CLICK_PERIMETER || Math.abs(roleY - npc.getY()) > NpcDataPool.NPC_CAN_CLICK_PERIMETER) {
                return false;
            }
        }

        return true;
    }

    /**
     * 显示中间点NPC
     */
    public void showNodeNpc(Role role, int npcId, boolean isBroadcast) {
        NPC npc = SpringUtils.getBean(MapService.class).getNpc(npcId);
        if (npc == null) {
            SchoolService schoolService = SpringUtils.getBean(SchoolService.class);
            byte toFightSchool = schoolService.getToFightSchool((byte) role.getPolar());
            npc = schoolService.getNpc(npcId, toFightSchool);
        }
        /**找不到对应NPC时不处理*/
        if (npc == null) {
            return;
        }
        if (npc.isShow() == false) {
            return;
        }
        if (npc.isMatchPolar((byte) role.getPolar()) == false) {
            return;
        }

        /**需要显示的NPC不在当前玩家地图时，不显示*/
        if (!SpringUtils.getBean(MapService.class).isInMap(role, npc.getMapId())) {
            return;
        }

        RespAppear respAppear = new RespAppear();
        respAppear.setRoleId(npc.getId());
        respAppear.setOrg_icon(npc.getIcon());
        respAppear.setPosX(npc.getX());
        respAppear.setPosY(npc.getY());
        /**设置为NPC类型*/
        respAppear.setType(Const.CHARATER_NPC);

        respAppear.setDir(npc.getFangxiang());
        respAppear.setRoleName(npc.getName());
        respAppear.setStatus(npc.getIcon());
        respAppear.setIcon(npc.getIcon());
        respAppear.setPortrait(npc.getIcon());
        respAppear.setWeaponId(npc.getWuqiId());
        respAppear.setSuit_icon(npc.getTaozhuangId());
        respAppear.setSuit_light_effect(npc.getFaguangId());


        MessagePusher.pushMessage(role, respAppear);
    }

    /**
     * 隐藏中间点NPC
     */
    public void hideNodeNpc(Role role, int npcId, boolean isBroadcast) {
        NPC npc = SpringUtils.getBean(MapService.class).getNpc(npcId);
        if (npc == null) {
            SchoolService schoolService = SpringUtils.getBean(SchoolService.class);
            byte toFightSchool = schoolService.getToFightSchool((byte) role.getPolar());
            npc = schoolService.getNpc(npcId, toFightSchool);
        }
        /**找不到对应NPC时不处理*/
        if (npc == null) {
            return;
        }

        /**需要隐藏的NPC不在当前玩家地图时，不处理*/
        if (!SpringUtils.getBean(MapService.class).isInMap(role, npc.getMapId())) {
            return;
        }

        RespDisappear respDisappear = new RespDisappear();
        respDisappear.setId(npcId);
        /**设置为NPC类型*/
        respDisappear.setType(Const.CHARATER_NPC);

        MessagePusher.pushMessage(role, respDisappear);
    }

    /**
     * 处理简单的按钮功能
     */
    public void npcButton(Role role, String msg, NPC npc) {
        switch (msg) {
            default: {
                break;
            }
            case "do_introduce": {  //娃娃介绍
                SpringUtils.getBean(WawaService.class).introduce(role);
                break;
            }
            case "do_obtain": {  //娃娃介绍
                SpringUtils.getBean(WawaService.class).do_obtain(role,npc);
                break;
            }
            case "回购物品或宠物":{
                MessagePusher.pushMessage(role,new RespBuyBackList());
                break;
            }
            case "我要位列仙班": {
                openDlg(role, "OnlineMallVIPDlg");
                break;
            }
            case "查看证道榜": {
                String dlg = "RankingListDlg=11|110{0}";
                openDlg(role, MessageFormat.format(dlg, role.getPolar()));
                break;
            }
            case "new_shidao_dahui_instruction": {
                openDlg(role, "ShiDaoDlg");
                break;
            }
            case "我要炼化套装": {
                openDlg(role, "EquipmentRefiningSuitDlg");
                break;
            }
            case "我要进化装备": {
                openDlg(role, "EquipmentEvolveDlg");
                break;
            }
            case "我要制作升级首饰": {
                openDlg(role, "JewelryUpgradeDlg");
                break;
            }
            case "我要改造装备": {
                openDlg(role, "EquipmentUpgradeDlg");
                break;
            }
            case "我要炼化属性": {
                openDlg(role, "EquipmentRefiningDlg");
                break;
            }
            case "我要拆分装备": {
                openDlg(role, "EquipmentSplitDlg");
                break;
            }
            case "存取物品": {
                openDlg(role, "StoreItemDlg");
                break;
            }
            case "存取宠物": {
                openDlg(role, "StorePetDlg");
                break;
            }
            case "存取金钱": {
                openDlg(role, "StoreMoneyDlg");
                break;
            }
            case "我要查看排行榜": {
                openDlg(role, "RankingListDlg");
                break;
            }
            case "到集市逛逛": {
                openDlg(role, "MarketBuyDlg");
                break;
            }
            case "我要买驱魔香": {
                sendNpcContent(role, npc, "近来妖怪作乱，鄙人观道长奔波辛苦，故请高人作法，将驱魔香移至主界面#R巡逻#n按钮中，并不再收取手续费，道长可放心使用。[离开]");
                break;
            }
            case "我准备好了": {
                openDlg(role, "PetCallDlg");
                break;
            }
            case "召唤精怪": {
                sendNpcContent(role, npc, "千兽图内气象万千，精怪无穷，若想成功召唤，至少需要一袋#R精怪诱饵#n及#cBA55DC5,000,000#n文钱#n，才能将精怪引出。道友准备好便可随我入千兽图阵中召唤精怪！[我准备好了][离开]");
                break;
            }
            case "精怪介绍": {
                sendNpcContent(role, npc, "道友想要了解哪些内容？[如何召唤精怪][如何驯化精怪][离开]");
                break;
            }
            case "如何召唤精怪": {
                sendNpcContent(role, npc, "精怪乃天地灵气所聚，由于长期受到灵气的淬炼，所以精怪不仅可以像宠物一样战斗，还有成为坐骑的潜质。贫道的千兽图内气象万千，精怪无穷，道友若想获得精怪，可携带一袋#R精怪诱饵#n与#cBA55DC5,000,000#n文钱#n前来，贫道自会帮助道友施法召唤精怪，不过召唤到是何种精怪，就要看道友的造化了。[如何驯化精怪][离开]");
                break;
            }
            case "如何驯化精怪": {
                sendNpcContent(role, npc, "精怪野性未除，桀骜不驯，并不适合骑乘。道友可携带#R拘首环#n、#R困灵砂#n、#R驱力刺#n、#R定鞍石#n、#R控心玉#n各1个，待贫道施展手段，必能将精怪驯化，使精怪变为可骑乘的#R御灵#n，还能增加#R30天#n风灵丸时间。[如何召唤精怪][离开]");
                break;
            }
            case "驯化精怪": {
                PetService petService = SpringUtils.getBean(PetService.class);
                Set<Integer> set = role.getPetBox().equippedPets(role);
                boolean isMount = true;
                for (Integer integer : set) {
                    if (petService.getPetById(integer, role).getItype() == 1) {
                        isMount = false;
                        break;
                    }
                }
                if (isMount) {
                    sendNpcContent(role, npc, "你身上没有精怪，让我如何驯化？[离开]");
                } else {
                    RespSubmitMultiItem respSubmitMultiItem = new RespSubmitMultiItem();
                    MessagePusher.pushMessage(role, respSubmitMultiItem);
                }
                break;
            }
            case "五行竞猜": {
                send(role);
                break;
            }
            case "我要做买卖": {//杂货店
                SpringUtils.getBean(ShopService.class).sendGroceryShop(role, npc);
                break;
            }
            case "买卖": {//药店
                List<String> list = npc.getList();
                List<ItemInfo> itemInfos = new ArrayList<>();
                short pos = 1;
                for (String name : list) {
                    ItemInfo itemInfo = new ItemInfo();
                    Medicine medicine = ShopDataPool.getMedicineBy(name);
                    if (medicine == null) {
                        continue;
                    }
                    itemInfo.setPos(pos);
                    itemInfo.setName(medicine.getKey_name());
                    itemInfo.setPrice(medicine.getPrice());
                    itemInfos.add(itemInfo);
                    pos++;
                }
                RespGoodsList respGoodsList = new RespGoodsList();
                respGoodsList.setNpcId(npc.getId());
                respGoodsList.setList(itemInfos);
                respGoodsList.setType((short) 0);
                MessagePusher.pushMessage(role, respGoodsList);
                break;
            }
            case "destroy": {
                //sendNpcContent(role, npc, "妙手回春，无所不能。[销毁贵重道具/destroy_item][回收贵重宠物/destroy_pet][离开]");
                sendNpcContent(role, npc, "妙手回春，无所不能。[回收贵重宠物/destroy_pet][离开]");
                break;
            }
            case "destroy_pet": {//销毁贵重宠物
                PetService petService = SpringUtils.getBean(PetService.class);
                String idStr = petService.getValuablePetIdstr(role);
                if (Strings.isEmpty(idStr)) {
                    sendNpcContent(role, npc, "道友身上没有携带贵重宠物，请先把要销毁的贵重宠物携带在身上。[离开]");
                } else {
                    RespDestroyValuableList respDestroyValuableList = new RespDestroyValuableList();
                    respDestroyValuableList.setType(Const.BUYBACK_TYPE_PET);
                    respDestroyValuableList.setId_str(idStr);
                    MessagePusher.pushMessage(role, respDestroyValuableList);
                }
                break;
            }
            case "destroy_item": {//销毁贵重物品 Todo:贵重道具暂时没写计算
                String idStr = SpringUtils.getEquipService().getValuableItemIdstr(role);
                if (Strings.isEmpty(idStr)) {
                    sendNpcContent(role, npc, "妙手回春，无所不能。[离开]");
                } else {
                    RespDestroyValuableList respDestroyValuableList = new RespDestroyValuableList();
                    respDestroyValuableList.setType(Const.BUYBACK_TYPE_EQUIPMENT);
                    respDestroyValuableList.setId_str(idStr);
                    MessagePusher.pushMessage(role, respDestroyValuableList);
                }
                break;
            }
            case "七杀试炼": {
                openDlg(role, "QiShaDlg");
                break;
            }
            case "九天真君挑战": {
                 MSGJiuTianRespMasterInfo msgJiuTianRespMasterInfo = JSONObject.parseObject(role.getJuntianJson(), MSGJiuTianRespMasterInfo.class);
                //MSGJiuTianRespMasterInfo msgJiuTianRespMasterInfo = (MSGJiuTianRespMasterInfo) JSONObject.toBean(JSONObject.fromObject(role.getJuntianJson()), MSGJiuTianRespMasterInfo.class);
                if(msgJiuTianRespMasterInfo==null){
                    msgJiuTianRespMasterInfo = role.getMsgjuntian();
                }
               MessagePusher.pushMessage(role, msgJiuTianRespMasterInfo);
                openDlg(role, "JiuTianDlg");
                break;
            }
            case "飞升仙魔": {
                if(role.getChildInfo().getType() == 3 || role.getChildInfo().getType() == 4){
                    broadcastService.getUpdateAppear(role);
                    openDlg(role, "UserChangeUpgradeDlg");
                }else{
                    MessagePusher.pushMessage(role, new RespNotifyMiscEx("道友实力尚浅，还没达到飞升标准，不可以进行仙魔转换！"));
                }
                break;
            }
			 case "fixedTeam": {
			     //请求固定队NPC
                 FixedTeamService repository = SpringUtils.getBean(FixedTeamService.class);
                 repository.requestItem(role,npc);
                //openDlg(role, "TeamVoteDlg");
                break;
            }
            case "quitFixedTeam": {
                //退出固定队
                FixedTeamService repository = SpringUtils.getBean(FixedTeamService.class);
                repository.quitFixedItem(role,npc);
                break;
            }
        }
    }


    public void send(Role role){
        RespOpenGuess respOpenGuess = new RespOpenGuess();
        respOpenGuess.setFlag((byte) 0);
        respOpenGuess.setMoney(0);  //未提取金钱
        respOpenGuess.setSurlus(String.valueOf(0));
        respOpenGuess.setOverflow("0");
        respOpenGuess.setAmount(0);
        respOpenGuess.setChoice((byte) 0);
        respOpenGuess.setPrize((byte) 0);
        respOpenGuess.setLeftCount((byte) SpringUtils.getActivityService().getRemainCount(role, ActivityType.XU_XING_JING_CAI));
        MessagePusher.pushMessage(role, respOpenGuess);
    }


    public void openDlg(Role role, String dlgName) {
        RespGeneralNotify respGeneralNotify = new RespGeneralNotify();
        respGeneralNotify.setNotify((short) NotifyModules.NOTIFY_OPEN_DLG); //打开对话框
        respGeneralNotify.setValue(dlgName);
        MessagePusher.pushMessage(role, respGeneralNotify);
    }


    public void closeDlg(Role role, String dlgName) {
        RespGeneralNotify respGeneralNotify = new RespGeneralNotify();
        respGeneralNotify.setNotify((short) NotifyModules.NOTIFY_CLOSE_DLG); //关闭对话框
        respGeneralNotify.setValue(dlgName);
        MessagePusher.pushMessage(role, respGeneralNotify);
    }
    //在线客服
    public void openOnlineUrl(Role role){
        RespPayUrl respPayUrl = new RespPayUrl();
        respPayUrl.setUrl(DataCache.REDIS_DATA.get("onlineCustomer"));
        MessagePusher.pushMessage(role, respPayUrl);
    }

    //增加属性点
    public void addPetAttribPoint(Role role,  RoleEquip roleEquip){
        /**没有参战宠物*/
        Pet pet = SpringUtils.getPetService().getPetById(role.getPetBox().getFightPetId(), role);
        if (pet== null) {
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("没有参战宠物"));
            return ;
        }
        String jiuzhuan_chongwu = DataCache.REDIS_DATA.get("jiuzhuan_chongwu");
        if( pet.getAddattrNumber() >= Integer.parseInt(jiuzhuan_chongwu)){
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("此宠物九转仙灵露使用数量达到上限"));
            return ;
        }
        //删除叠加物品
        if (SpringUtils.getBean(EquipService.class).delEquipNum(role, roleEquip, 1) <= 0) {
            return;
        }
        pet.setAddattrNumber( pet.getAddattrNumber()+1);
        PetService bean = SpringUtils.getBean(PetService.class);
        bean.refreshPetInfo(role, pet);
        String msg = "恭喜你，你的宠物增加了一点可分配属性点。当前增加了#Y%s#n点，上限#Y%s#n点";
        msg = String.format(msg,pet.getAddattrNumber(), jiuzhuan_chongwu);
        MessagePusher.pushMessage(role, new RespNotifyMiscEx(msg));
    }
    //获取NPC对话
    public void getAttribPointContent(Role role){
        String content = "#R属性点礼包,道友可以自选四中属性加成中的一种。#n[加成1点力量属性/attrib_li][加成1点灵力属性/attrib_fa][加成1点体质属性/attrib_ti][加成1点敏捷属性/attrib_min]";
        SpringUtils.getBean(NewNpcService.class).requestNpcContent(role, 15025,content);
    }
    public void getBookContent(Role role){
        StringBuilder content = new StringBuilder("选择满属性天书。");
        for (String superName : EquipService.superNames) {
            content.append("[");
            content.append(superName);
            content.append("/");
            content.append("selectsuperbook_");
            content.append(superName);
            content.append("]");
        }
        SpringUtils.getBean(NewNpcService.class).requestNpcContent(role, 15025,content.toString());
    }
    public void getManBook(Role role,String msg){
        RoleEquip roleEquip = SpringUtils.getBean(EquipService.class).getRoleEquipByName(role, "成品天书礼包");
        if (SpringUtils.getBean(EquipService.class).delEquipNum(role, roleEquip, 1) <= 0) {
            return;
        }
        if(msg.startsWith("selectsuperbook_")){
            OnlineMall onlineMall = new OnlineMall();
            onlineMall.setName(msg.split("_")[1]);
            onlineMall.setItemtype((short) 13);
            onlineMall.setType(16518);
            short pos = SpringUtils.getBean(BagService.class).getPos(role, false);
            SpringUtils.getBean(MallService.class).buyManBook(role, onlineMall, 1, true, pos);

        }
    }
    //增加属性点
    public void ceshi(Role role, String msg){
//        /**没有参战宠物*/
//        Pet pet = SpringUtils.getPetService().getPetById(role.getPetBox().getFightPetId(), role);
//        if (pet== null) {
//            return ;
//        }
//        pet.setAddattrNumber( pet.getAddattrNumber()+1);
//        PetService bean = SpringUtils.getBean(PetService.class);
//        bean.refreshPetInfo(role, pet);
    }
    //增加属性点
    public void addRoleAttribPoint(Role role, String msg){
        int type=0;
        int count = 0;
        String name = "";
        switch (msg){
            case "attrib_li":
                type=1;
                count = role.getExtendBox().getAddRoleStr();
                name = "力量";
                break;
            case "attrib_fa":
                type=2;
                count = role.getExtendBox().getAddRoleWiz();
                name = "灵力";
                break;
            case "attrib_ti":
                type=3;
                count = role.getExtendBox().getAddRoleCon();
                name = "体质";
                break;
            case "attrib_min":
                type=4;
                count = role.getExtendBox().getAddRoleDex();
                name = "敏捷";
                break;
        }
        String jiuzhuan_renwu = DataCache.REDIS_DATA.get("jiuzhuan_renwu_"+msg);
        if( count >= Integer.parseInt(jiuzhuan_renwu)){
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("人物九转仙灵露"+name+"达到使用上限"));
            return ;
        }
        RoleEquip roleEquip = SpringUtils.getBean(EquipService.class).getRoleEquipByName(role, "九转仙灵露·人物");
        //删除叠加物品
        if (SpringUtils.getBean(EquipService.class).delEquipNum(role, roleEquip, 1) <= 0) {
            return;
        }

        if(type == 1){
            role.getExtendBox().setAddRoleStr( count+1);
        }else if(type == 2){
            role.getExtendBox().setAddRoleWiz(  count +1 );
        }else if(type == 3){
            role.getExtendBox().setAddRoleCon(  count +1 );
        }else if(type == 4){
            role.getExtendBox().setAddRoleDex( count+1);
        }
        //赠送相性，刷新属性
        SpringUtils.getBean(RoleService.class).sendExtraAttribute(role);
        String message = "恭喜你成功使用九转仙灵露增加了一点"+name+"属性值。当前增加了#Y%s#n点，上限#Y%s#n点";
        message = String.format(message,count+1, jiuzhuan_renwu);
        MessagePusher.pushMessage(role, new RespNotifyMiscEx(message));
    }

    //增加属性点
    public void addRolePolorPoint(Role role,  RoleEquip roleEquip){
        int type  = DataCache.USE_BAG_DATA_MAP.get(roleEquip.getName());
        PlayerExtendBox extendBox = role.getExtendBox();
        int limitCount = 0;
        int useCount = 0;
        if(type == 1){
            useCount = extendBox.getPolor1();
            limitCount = Integer.parseInt(DataCache.REDIS_DATA.get("qianjinsan"));
        }else if(type == 2){
            useCount = extendBox.getPolor2();
            limitCount = Integer.parseInt(DataCache.REDIS_DATA.get("shenmuwan"));
        }else if(type == 3){
            useCount = extendBox.getPolor3();
            limitCount = Integer.parseInt(DataCache.REDIS_DATA.get("roushuidan"));
        }else if(type == 4){
            useCount = extendBox.getPolor4();
            limitCount = Integer.parseInt(DataCache.REDIS_DATA.get("luohuosan"));
        }else if(type == 5){
            useCount = extendBox.getPolor5();
            limitCount = Integer.parseInt(DataCache.REDIS_DATA.get("santuwan"));
        }
        if( useCount >= limitCount){
            MessagePusher.pushMessage(role, new RespNotifyMiscEx(roleEquip.getName()+"使用数量达到上限"));
            return ;
        }
        //删除叠加物品
        if (SpringUtils.getBean(EquipService.class).delEquipNum(role, roleEquip, 1) <= 0) {
            return;
        }
        //赠送相性，刷新属性
        if(type == 1){
            extendBox.setPolor1(useCount+1);
        }else if(type == 2){
            extendBox.setPolor2(useCount+1);
        }else if(type == 3){
            extendBox.setPolor3(useCount+1);
        }else if(type == 4){
            extendBox.setPolor4(useCount+1);
        }else if(type == 5){
            extendBox.setPolor5(useCount+1);
        }
        SpringUtils.getBean(RoleService.class).sendExtraAttribute(role);
        String message = "恭喜你成功使用"+roleEquip.getName()+"增加了一点相性。当前增加了#Y%s#n点，上限#Y%s#n点";
        message = String.format(message,useCount+1, limitCount);
        MessagePusher.pushMessage(role, new RespNotifyMiscEx(message));
    }

    //宠物兑换属性
    public void exchangeAttrByPet(Role role, String msg){
        int duihuanchongwuLimit = Integer.parseInt(DataCache.REDIS_DATA.get("duihuanchongwu_xianzhi"));
        int duihuanchongwu = role.getExtendBox().getDuihuanchongwu();
        if(duihuanchongwu >= duihuanchongwuLimit){
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("神兽宠物兑换次数已达上限！"));
            return;
        }

        PetService petService = SpringUtils.getBean(PetService.class);
        //String exchange_attr_pet_num = DataCache.REDIS_DATA.get("exchange_attr_pet_num1");
        String exchange_attr_pet_num = DataCache.REDIS_DATA.get(msg);
        String petName = exchange_attr_pet_num.split("-")[0];
        int petNum = Integer.parseInt(exchange_attr_pet_num.split("-")[1]);
        String addAttr =exchange_attr_pet_num.split("-")[2];
        List<Pet> pets = petService.getPetByName(petName, role);
        if(petNum>pets.size()){
            MessagePusher.pushMessage(role, new RespNotifyMiscEx(petName+"宠物数量不足"+petNum+"只"));
            return;
        }
        for (int i = 0; i < petNum; i++) {
            Pet pet = pets.get(i);
            petService.delPet(role, pet);//删除宠物
        }
        //发送属性
        JSONArray titleJars = JSONObject.parseArray(addAttr);
        PlayerExtendBox extendBox = role.getExtendBox();
        for (Object titleJar : titleJars) {
            JSONObject jsonObject =(JSONObject)titleJar;
            String field = jsonObject.getString("field");
            int num = jsonObject.getIntValue("value");
            if("所有相性".equals(field)){
                extendBox.setPetAllPolorNum(extendBox.getPetAllPolorNum() + num);
            }
            if("所有属性".equals(field)){
                extendBox.setPetAllAttrNum(extendBox.getPetAllAttrNum() + num );
            }
        }
        duihuanchongwu +=1;
        role.getExtendBox().setDuihuanchongwu(duihuanchongwu);
        SpringUtils.getBean(RoleService.class).sendExtraAttribute(role);
        String message = "恭喜你成功使用"+petNum+"个"+petName+"兑换了一次属性加成,当前神兽宠物已兑换"+duihuanchongwu + "次，共可兑换"+duihuanchongwuLimit+"次";
        MessagePusher.pushMessage(role, new RespNotifyMiscEx(message));
    }

    public void exchangeAttrByPetbianyi(Role role, String msg){
        int duihuanchongwuLimit = Integer.parseInt(DataCache.REDIS_DATA.get("bianyiduihuanchongwu_xianzhi"));
        int duihuanchongwu = role.getExtendBox().getDuihuanchongwu1();
        if(duihuanchongwu >= duihuanchongwuLimit){
            MessagePusher.pushMessage(role, new RespNotifyMiscEx("变异宠物兑换次数已达上限！"));
            return;
        }

        PetService petService = SpringUtils.getBean(PetService.class);
        //String exchange_attr_pet_num = DataCache.REDIS_DATA.get("exchange_attr_pet_num1");
        String exchange_attr_pet_num = DataCache.REDIS_DATA.get(msg);
        String petName = exchange_attr_pet_num.split("-")[0];
        int petNum = Integer.parseInt(exchange_attr_pet_num.split("-")[1]);
        String addAttr =exchange_attr_pet_num.split("-")[2];
        List<Pet> pets = petService.getPetByName(petName, role);
        if(petNum>pets.size()){
            MessagePusher.pushMessage(role, new RespNotifyMiscEx(petName+"宠物数量不足"+petNum+"只"));
            return;
        }
        for (int i = 0; i < petNum; i++) {
            Pet pet = pets.get(i);
            petService.delPet(role, pet);//删除宠物
        }
        //发送属性
        JSONArray titleJars = JSONObject.parseArray(addAttr);
        PlayerExtendBox extendBox = role.getExtendBox();
        for (Object titleJar : titleJars) {
            JSONObject jsonObject =(JSONObject)titleJar;
            String field = jsonObject.getString("field");
            int num = jsonObject.getIntValue("value");
            if("所有相性".equals(field)){
                extendBox.setPetAllPolorNum(extendBox.getPetAllPolorNum() + num);
            }
            if("所有属性".equals(field)){
                extendBox.setPetAllAttrNum(extendBox.getPetAllAttrNum() + num );
            }
        }
        duihuanchongwu +=1;
        role.getExtendBox().setDuihuanchongwu1(duihuanchongwu);
        SpringUtils.getBean(RoleService.class).sendExtraAttribute(role);
        String message = "恭喜你成功使用"+petNum+"个"+petName+"兑换了一次属性加成,当前变异宠物已兑换"+duihuanchongwu + "次，共可兑换"+duihuanchongwuLimit+"次";
        MessagePusher.pushMessage(role, new RespNotifyMiscEx(message));
    }


    //天书洗练
    //获取NPC对话
    public void getBookXilianContent(Role role, String msg, NPC npc){
        // String content = "属性点礼包。[加成力量属性/attrib_li][加成灵力属性/attrib_fa][加成体质属性/attrib_ti][加成敏捷属性/attrib_min]";
        //获取参战宠物ID
        if("洗练金色天书".equals(msg)){
            int count = Integer.parseInt(DataCache.REDIS_DATA.get("book_xilian_xiaohao"));
            int fightPetId = role.getPetBox().getFightPetId();
            String content = "每次洗练天书消耗："+count+"积分";
            Map<Integer, PetBook> bookHashMap = role.getPetBox().getPetBooks(fightPetId);
            for (Map.Entry<Integer, PetBook> integerPetBookEntry : bookHashMap.entrySet()) {
                if(integerPetBookEntry.getValue().getIsSuper() == 1){
                    PetBook value = integerPetBookEntry.getValue();
                    content += "[洗练天书-"+value.getBookName()+"]";
                }
            }
            sendNpcContent(role, npc, content);
        }else if(msg.startsWith("洗练天书")) {
            String bookName = msg.replaceAll("洗练天书-", "");
            String content = "洗练" + bookName;
            content += "[洗练属性-气血/xilianshuxing_气血_"+bookName+"]";
            content += "[洗练属性-物伤/xilianshuxing_物伤_"+bookName+"]";
            content += "[洗练属性-法伤/xilianshuxing_法伤_"+bookName+"]";
            content += "[洗练属性-速度/xilianshuxing_速度_"+bookName+"]";
            content += "[洗练属性-防御/xilianshuxing_防御_"+bookName+"]";
            sendNpcContent(role, npc, content);
        }else if(msg.startsWith("xilianshuxing_")){
            int count = Integer.parseInt(DataCache.REDIS_DATA.get("book_xilian_xiaohao"));
            int before = role.getActivity().getRechargeScore();
            if(count>before){
                MessagePusher.pushMessage(role, new RespNotifyMiscEx("积分不足!"));
                return;
            }
            String bookName = msg.split("_")[2];
            String type = msg.split("_")[1];
            int fightPetId = role.getPetBox().getFightPetId();
            Pet pet = role.getPetBox().getPetByPetId(fightPetId);
            Map<Integer, PetBook> bookHashMap = role.getPetBox().getPetBooks(fightPetId);
            PetBook petBook = null ;
            for (Map.Entry<Integer, PetBook> integerPetBookEntry : bookHashMap.entrySet()) {
                if(bookName.equals(integerPetBookEntry.getValue().getBookName())){
                    petBook = integerPetBookEntry.getValue();
                }
            }
            if(petBook != null){
                RoleEquip roleEquip = role.getEquipBox().getRoleEquip(petBook.getRoleEquipId());
                SpringUtils.getBean(MallService.class).addGoldBook(roleEquip,type,role);
                SpringUtils.getBean(EquipService.class).refreshRoleEquip(role, roleEquip);
                SpringUtils.getPetService().refreshPetInfo(role, pet);
            }
        }
    }
}
